﻿using System;
using System.Threading.Tasks;
using SmartCity.Shared;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace MetroManagement
{
    /// <summary>
    /// 乘车卡应用服务类
    /// </summary>
    public class CardAppService : ApplicationService, ICardAppService
    {
        private readonly IAuthManager _authManager;
        private readonly CardManager _cardManager;
        private readonly IRepository<Card, int> _cardRepository;

        public CardAppService(
            IAuthManager authManager,
            CardManager cardManager,
            IRepository<Card, int> cardRepository)
        {
            _authManager = authManager;
            _cardManager = cardManager;
            _cardRepository = cardRepository;
        }

        // 获取
        public async Task<ResultResponse<CardDto>> GetAsync()
        {
            var userId = _authManager.GetUserId();
            var card = await _cardRepository.FirstOrDefaultAsync(m => m.UserId == userId);
            if (card == null)
                return ResultResponse<CardDto>.Failed("未领取乘车卡");
            var dto = ObjectMapper.Map<Card, CardDto>(card);
            return ResultResponse<CardDto>.Successful(dto);
        }

        // 领取
        public async Task<ActionResponse> CreateAsync(CreateCardDto input)
        {
            var userId = _authManager.GetUserId();
            if (await _cardRepository.AnyAsync(m => m.UserId == userId))
                return ActionResponse.Failed("您已领取乘车卡，不可重复领取！");
            var cardNum = DateTime.Now.ToString("yyyyMMddHHmmssfff");
            await _cardManager.CreateAsync(
                userId,
                input.UserName,
                input.IdCard,
                input.Phonenumber,
                cardNum);
            return ActionResponse.Successful();
        }

        // 注销
        public async Task<ActionResponse> DeleteAsync(int id)
        {
            await _cardRepository.DeleteAsync(id);
            return ActionResponse.Successful();
        }
    }
}